package daosbd;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import excecoes.DAOException;
import java.lang.reflect.ParameterizedType;

public class DaoGenericoJPA<T> implements DAOGenerico<T>
{
	private Class<T> classEntity;
	protected static final EntityManagerFactory fabrica = Persistence.createEntityManagerFactory("allaboutmybook");
	
	
	@SuppressWarnings("unchecked")
	public DaoGenericoJPA() 
	{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.classEntity = (Class<T>)
		((ParameterizedType) getClass().getGenericSuperclass()).
		getActualTypeArguments()[0];
		}
	
	@Override
	public void adicionarEntidade(T entidade) throws DAOException 
	{
		EntityManager manager = fabrica.createEntityManager();
		try 
		{
			manager.getTransaction().begin();
			manager.persist(entidade);
			manager.getTransaction().commit();
		} 
		catch (Exception e) 
		{ 
			throw new DAOException(e);
		}
	}
	
	@Override
	public void updateEntidade(T entidade) throws DAOException 
	{
		EntityManager manager = fabrica.createEntityManager();
		try 
		{
			manager.getTransaction().begin();
			manager.merge(entidade);
			manager.getTransaction().commit();
		} 
		catch (Exception e) 
		{ 
			throw new DAOException(e);
		}
		
	}
	@Override
	public void removerEntidade(String chaveEntidade) throws DAOException 
	{
		System.out.println("<><><><> apagar no DAOConcreto:" + chaveEntidade);
		EntityManager manager = fabrica.createEntityManager();
		try 
		{
			manager.getTransaction().begin();
			T entidade = manager.find(classEntity, chaveEntidade);
			if(entidade != null)
			{
				manager.remove(entidade);
			}
			manager.getTransaction().commit();
		} 
		catch (Exception e) 
		{
			System.out.println("///////////////////excecao em DAOgenericoJPA");
			e.printStackTrace();
			throw new DAOException(e);
		}
		
	}
	@Override
	public List encontrarTodos() throws DAOException 
	{
		EntityManager manager = fabrica.createEntityManager();
		try 
		{
			String query = "from " + classEntity.getSimpleName();
			return manager.createQuery(query).getResultList();
		} 
		catch (Exception e) 
		{
			System.out.println("///////////////////excecao em DAOgenericoJPA");
			e.printStackTrace();
			throw new DAOException(e);
		} 
		finally 
		{
			if (manager != null) { manager.close(); }
		}
	}
	@Override
	public T encontrarPorId(Serializable id) throws DAOException 
	{
		EntityManager manager = fabrica.createEntityManager();
		try 
		{
			return manager.find(classEntity, id);
		} 
		catch (Exception e) 
		{
			throw new DAOException(e);
		} 
		finally 
		{
			if (manager != null) 
			{ 	manager.close();
			}
			
		}
		
	}

}